package msg;

import com.rabbitmq.client.*;
import config.Config;
import org.apache.log4j.Logger;
import use.FileUse;


public class MsgManager {
    private Logger logger = Logger.getLogger(MsgManager.class);
    private static MsgManager instance;
    public static MsgManager getInstance() {
        if (instance == null) {
            instance = new MsgManager();
        }
        return instance;
    }

    private Connection conn;
    private Channel channel;
    public final static String EXCHANGE = "lockExchange";
    public void rabbitInit(){
        try{
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(Config.Rabbit_Host);
            factory.setPort(Config.Rabbit_Port);
            factory.setUsername(Config.Rabbit_Username);
            factory.setPassword(Config.Rabbit_Password);
            factory.setVirtualHost("/");
            factory.setAutomaticRecoveryEnabled(true);
            conn = factory.newConnection();
            channel = conn.createChannel();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void msg_send(String msg){
        msg_send_by_queue(Config.Rabbit_Send_Queue,msg);
    }

    public void msg_send_by_queue(String queue,String msg){
        try{
            channel.queueDeclare(queue, false, false, false, null);
            channel.basicPublish("", queue, null, msg.getBytes());
            logger.info(String.format("send %s msg : %s ",queue,msg));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void msg_recv(String queue){
        try{
            Channel channel = conn.createChannel();
            channel.queueDeclare( queue, false, false, false, null);
            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                    MsgHandle.getInstance().msg_switch(new String(body));
                }
            };
            channel.basicConsume(queue, true, consumer);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
